//
// Created by Administrator on 2021/2/22 0022.
//

#ifndef MY_APPLICATION_GIFDECODER_H
#define MY_APPLICATION_GIFDECODER_H

#include <jni.h>
#include "Stream.h"
#include "../giflib/gif_lib.h"
#include "Color.h"

int GifDecoder_OnLoad(JNIEnv *env);

class GifDecoder {

private:
    bool mHasInit = false;
    GifFileType *mGif;
    bool *mPreservedFrames = NULL;
    int *mRestoringFrames = NULL;
    // 缓存 Gif 的背景色
    Color8888 mBgColor = TRANSPARENT;

    // 缓存上一帧的 Bitmap 数据
    Color8888 *mPreserveBuffer = NULL;
    // 缓存上一帧的 SampleSize
    int mPreserveSampleSize = 1;
    // 上一帧的 FrameNumber
    int mPreserveBufferFrame;


    long mDurationMs = 0l;
    int mLoopCount = 1;


    void init();

    // 获取上一帧数据
    bool getPreservedFrame(int frameIndex) const { return mPreservedFrames[frameIndex]; }

    int getRestoringFrame(int frameIndex) const { return mRestoringFrames[frameIndex]; }

    // 缓存上一帧的数据
    void savePreserveBuffer(Color8888 *outputPtr, int outputPixelStride, int frameNr, int inSampleSize);

    // 从上一帧中恢复数据
    void restorePreserveBuffer(Color8888 *outputPtr, int outputPixelStride, int inSampleSize);


public:
    /**
     * @param stream 处理原始Gif流信息
     */
    GifDecoder(Stream *stream);

    /**
     * @param filePath 处理Gif图片
     */
    GifDecoder(char *filePath);

    ~ GifDecoder();

    bool hasInit() const;

    int getWith();

    int getHeight();

    bool isOpeque() const;

    int getFrameCount();

    int getLooperCount() const;

    long getDuration() const;

    long drawFrame(int frameNr, Color8888 *outputPtr, int outputPixelStride, int previousFrameNr,
                   int inSampleSize);
};

#endif //MY_APPLICATION_GIFDECODER_H
